/**
 * 
 */
package com.netflexitysolutions.amazonws.sdb.orm.internal;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.netflexitysolutions.amazonws.sdb.orm.SimpleDBSession;
import com.netflexitysolutions.amazonws.sdb.orm.SimpleDBSessionListener;
import com.netflexitysolutions.amazonws.sdb.orm.metadata.ItemMetadata;

/**
 * @author netflexity
 *
 */
public class CacheSessionListener implements SimpleDBSessionListener {

	private SimpleDBSession session;
	private Map<String, Boolean> loadMap = Collections.synchronizedMap(new HashMap<String, Boolean>());
	
	/**
	 * @param session
	 */
	public CacheSessionListener(SimpleDBSession session) {
		this.session = session;
	}

	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.orm.SimpleDBSessionListener#afterRemove(java.lang.Object)
	 */
	public <T> void afterRemove(T removedRecord) {
		
	}

	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.orm.SimpleDBSessionListener#afterSave(java.lang.Object)
	 */
	public <T> void afterSave(T savedRecord) {
		
	}

	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.orm.SimpleDBSessionListener#beforeRemove(java.lang.Object)
	 */
	public <T> void beforeRemove(T record) {
		
	}

	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.orm.SimpleDBSessionListener#beforeSave(java.lang.Object, java.lang.Object)
	 */
	public <T> void beforeSave(T newRecord, T oldRecord) {
		
	}

	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.orm.SimpleDBSessionListener#beforeSelect(com.netflexitysolutions.amazonws.sdb.orm.metadata.ItemMetadata)
	 */
	public <T> void beforeSelect(ItemMetadata metadata) {
		synchronized (loadMap) {
			if(metadata.isCachable() && !loadMap.containsKey(metadata.getClassName())){
				session.findAllAsync(metadata.getJavaClass());
				loadMap.put(metadata.getClassName(), true);
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.orm.SimpleDBSessionListener#initialize(java.lang.Object)
	 */
	public <T> void initialize(T record) {
		
	}
}
